package com.kf.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kf.config.AliyunOSSUtil;
import com.kf.config.SecurityUser;
import com.kf.handler.MyException;
import com.kf.mapper.*;
import com.kf.pojo.*;
import com.kf.pojo.form.*;
import com.kf.service.TeacherService;
import com.kf.service.UserService;
import com.kf.util.MD5Utils;
import com.kf.util.R;
import com.kf.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>
 * 教师表 服务实现类
 * </p>
 *
 * @author 康峰
 * @since 2022-10-31
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    TeacherMapper teacherMapper;
    @Autowired
    ChoCgyRecordMapper choCgyRecordMapper;
    @Autowired
    ChoCgyMapper choCgyMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Resource
    AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    UserService userService;
    @Autowired
    GradeMapper gradeMapper;
    @Autowired
    PaperFileMapper paperFileMapper;
    @Autowired
    RecordsMapper recordsMapper;
    @Autowired
    ReportMapper reportMapper;
    @Autowired
    WenFileMapper wenFileMapper;
    @Autowired
    DefenceMapper defenceMapper;
    @Autowired
    NoticeMapper noticeMapper;
    @Autowired
    NoticefileMapper noticefileMapper;
    @Autowired
    ReportFileMapper reportFileMapper;
    @Override
    public void insert(Teacher teacher) {
        teacherMapper.insert(teacher);
    }

    @Override
    public void updateSelf(Teacher teacher) {
        teacherMapper.updateById(teacher);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void cheChoRecord(CheckCgyForm checkCgyForm) {
        QueryWrapper<ChoCgyRecord> choCgyRecordQueryWrapper = new QueryWrapper<>();
        choCgyRecordQueryWrapper.eq("id",checkCgyForm.getCgyId());
        ChoCgyRecord choCgyRecord = choCgyRecordMapper.selectOne(choCgyRecordQueryWrapper);
        choCgyRecord.setStatus(checkCgyForm.getCgyStatus());
        choCgyRecord.setAdvise(checkCgyForm.getCgyAdvise());
        if(choCgyRecord.getStatus()==1){
            QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
            choCgyQueryWrapper.eq("user_id", choCgyRecord.getUserId());
            choCgyMapper.delete(choCgyQueryWrapper);
            System.out.println("chocgy删除了");
        }

        choCgyRecordMapper.updateById(choCgyRecord);


        if(choCgyRecord.getStatus()==2){
            ChoCgy choCgy = new ChoCgy();
            choCgy.setCgyId(choCgyRecord.getCgyId()).setSusername(choCgyRecord.getSusername()).setTusername(choCgyRecord.getTusername())
                    .setTeaName(choCgyRecord.getTeaName())
                    .setCgyName(choCgyRecord.getCgyName());
            choCgyMapper.insert(choCgy);
        }
    }

    @Override
    public  PageForm<ChoCgyRecord> pageChoMy(ChoMyForm choMyForm) {
        User user = SecurityUser.getUser();
        QueryWrapper<ChoCgyRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tusername",user.getUsername());
        if(choMyForm.getStatus()!=3){
            queryWrapper.eq("status",choMyForm.getStatus());
        }
        if(choMyForm.getCgySource()!=3){
            queryWrapper.eq("cgy_source",choMyForm.getCgySource());
        }
        if(choMyForm.getSusername()!=null){
            queryWrapper.like("susername",choMyForm.getSusername());
        }

        Page<ChoCgyRecord> choCgyRecordPage = new Page<>(choMyForm.getCurrent(), choMyForm.getSize());
        IPage<ChoCgyRecord> choCgyRecordIPage = choCgyRecordMapper.selectPage(choCgyRecordPage, queryWrapper);
        List<ChoCgyRecord> choCgyRecords = choCgyRecordIPage.getRecords();
        PageForm<ChoCgyRecord> choCgyRecordPageForm = new PageForm<>();
        choCgyRecordPageForm.setList(choCgyRecords);
        choCgyRecordPageForm.setTotal(choCgyRecordIPage.getTotal());
        return choCgyRecordPageForm;
    }

    @Override
    public void batchCheckRecord(CheckList<Integer> checkList) {
        List<Integer> list = checkList.getList();
        for (Integer integer : list) {
            QueryWrapper<ChoCgyRecord> choCgyRecordQueryWrapper = new QueryWrapper<>();
            choCgyRecordQueryWrapper.eq("id",integer);
            ChoCgyRecord choCgyRecord = choCgyRecordMapper.selectOne(choCgyRecordQueryWrapper);
            choCgyRecord.setStatus(checkList.getStatus()).setAdvise(checkList.getAdvise());
            choCgyRecordMapper.updateById(choCgyRecord);
            if(choCgyRecord.getStatus()==1){
                QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
                categoryQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                List<Category> categories = categoryMapper.selectList(categoryQueryWrapper);
                if(categories!=null){
                    categories.forEach(x->{
                        x.setCgyStatus(1);
                        x.setCgyLeadstatus(1);
                        categoryMapper.updateById(x);
                    });
                }


                QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
                choCgyQueryWrapper.eq("user_id", choCgyRecord.getUserId());
                QueryWrapper<PaperFile> paperFileQueryWrapper1 = new QueryWrapper<>();
                paperFileQueryWrapper1.eq("user_id",choCgyRecord.getUserId());
                PaperFile paperFile = paperFileMapper.selectOne(paperFileQueryWrapper1);
                if(paperFile!=null){
                    aliyunOSSUtil.deleteFile(paperFile.getPath() + "/" + paperFile.getFilename() + "." + paperFile.getSuffix());
                    QueryWrapper<PaperFile> paperFileQueryWrapper = new QueryWrapper<>();
                    paperFileQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                    paperFileMapper.delete(paperFileQueryWrapper);
                }
                QueryWrapper<WenFile> wenFileQueryWrapper = new QueryWrapper<>();
                wenFileQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                WenFile wenFile = wenFileMapper.selectOne(wenFileQueryWrapper);
                if(wenFile!=null){
                    aliyunOSSUtil.deleteFile(wenFile.getPath()+"/"+wenFile.getFilename()+"."+ wenFile.getSuffix());
                    QueryWrapper<WenFile> wenFileQueryWrapper1 = new QueryWrapper<>();
                    wenFileQueryWrapper1.eq("user_id",choCgyRecord.getUserId());
                    wenFileMapper.delete(wenFileQueryWrapper1);
                }

                QueryWrapper<Report> reportQueryWrapper = new QueryWrapper<>();
                reportQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                reportMapper.delete(reportQueryWrapper);
                QueryWrapper<Records> recordsQueryWrapper = new QueryWrapper<>();
                recordsQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                recordsMapper.delete(recordsQueryWrapper);
                QueryWrapper<Records> recordsQueryWrapper1 = new QueryWrapper<>();
                recordsQueryWrapper1.eq("re_target",choCgyRecord.getSusername());
                recordsMapper.delete(recordsQueryWrapper1);


                choCgyMapper.delete(choCgyQueryWrapper);

                System.out.println("chocgy删除了");
            }else if(choCgyRecord.getStatus()==2){
                if(choCgyRecord.getCgySource()==1){
                    throw new MyException(ResultCode.CATEGORY_CHECK_ERROR);
                }
                QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
                choCgyQueryWrapper.eq("user_id",choCgyRecord.getUserId());
                ChoCgy choCgy1 = choCgyMapper.selectOne(choCgyQueryWrapper);
                if(choCgy1==null){
                    ChoCgy choCgy = new ChoCgy();
                    choCgy.setCgyId(choCgyRecord.getCgyId())
                            .setStuName(choCgyRecord.getStuName())
                            .setUserId(choCgyRecord.getUserId());
                    choCgy.setSusername(choCgyRecord.getSusername());
                    choCgy.setTusername(choCgyRecord.getTusername());
                    choCgy.setTeaName(choCgyRecord.getTeaName());
                    choCgy.setCgyName(choCgyRecord.getCgyName());
                    choCgy.setCgySource(choCgyRecord.getCgySource());
                    choCgyMapper.insert(choCgy);
                }else {
                    choCgy1.setCgyId(choCgyRecord.getCgyId())
                            .setStuName(choCgyRecord.getStuName())
                            .setUserId(choCgyRecord.getUserId());
                    choCgy1.setSusername(choCgyRecord.getSusername());
                    choCgy1.setTusername(choCgyRecord.getTusername());
                    choCgy1.setTeaName(choCgyRecord.getTeaName());
                    choCgy1.setCgyName(choCgyRecord.getCgyName());
                    choCgy1.setCgySource(choCgyRecord.getCgySource());
                    choCgyMapper.updateById(choCgy1);
                }

            }
        }
    }

    @Override
    public Teacher findById(int userId) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("user_id",userId);
        Teacher teacher = teacherMapper.selectOne(teacherQueryWrapper);
        return teacher;
    }

    @Override
    public List<Teacher> selectList(User user) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tea_department",user.getDepartment());
        List<Teacher> teachers = teacherMapper.selectList(queryWrapper);
        return teachers;

    }

    @Override
    public IPage<Category> pageCategory(SelectForm selectForm) {
        Page<Category> categoryPage = new Page<>(selectForm.getCurrent(), selectForm.getSize());
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();

        categoryQueryWrapper.like("cgy_name",selectForm.getName()).or()
                .like("tusername",selectForm.getName()).eq("deleted",0);
        IPage<Category> categoryIPage = categoryMapper.selectPage(categoryPage, categoryQueryWrapper);
        return categoryIPage;


    }

    @Override
    public void updateTeacher(User user, TeacherForm teacherForm, Teacher teacher) {

        int userId = user.getUserId();


        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("tusername",user.getUsername());
        List<Category> categories = categoryMapper.selectList(categoryQueryWrapper);
        categories.forEach(x->{
            x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
            categoryMapper.updateById(x);
        });



        QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
        choCgyQueryWrapper.eq("tusername",user.getUsername());
        List<ChoCgy> choCgies = choCgyMapper.selectList(choCgyQueryWrapper);
        if(choCgies!=null){
            choCgies.forEach(x->{
                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
                choCgyMapper.updateById(x);
            });

        }


        QueryWrapper<ChoCgyRecord> choCgyRecordQueryWrapper = new QueryWrapper<>();
        choCgyRecordQueryWrapper.eq("tusername",user.getUsername());
        List<ChoCgyRecord> choCgyRecords = choCgyRecordMapper.selectList(choCgyRecordQueryWrapper);
        if(choCgyRecords!=null){
            choCgyRecords.forEach(x->{
                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
                choCgyRecordMapper.updateById(x);
            });
        }

        List<Defence> defences = defenceMapper.selectList(null);
        defences.forEach(x->{
            if(x.getTusername().equals(user.getUsername())){
                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
                defenceMapper.updateById(x);
            }
            if(x.getTusername1().equals(user.getUsername())){
                x.setTusername1(teacherForm.getUsername()).setTeaname1(teacherForm.getTeaName());
                defenceMapper.updateById(x);
            }
            if(x.getTusername2().equals(user.getUsername())){
                x.setTusername2(teacherForm.getUsername()).setTeaname2(teacherForm.getTeaName());
                defenceMapper.updateById(x);
            }
            if(x.getTusername3().equals(user.getUsername())){
                x.setTusername3(teacherForm.getUsername()).setTeaname3(teacherForm.getTeaName());
                defenceMapper.updateById(x);
            }
            if(x.getTusername4().equals(user.getUsername())){
                x.setTusername4(teacherForm.getUsername()).setTeaname4(teacherForm.getTeaName());
                defenceMapper.updateById(x);
            }
        });


        QueryWrapper<Notice> noticeQueryWrapper = new QueryWrapper<>();
        noticeQueryWrapper.eq("user_id",userId);
        List<Notice> notices = noticeMapper.selectList(noticeQueryWrapper);
        if(notices!=null){
            notices.forEach(x->{
                x.setCreateby(teacherForm.getTeaName()).setUsername(teacherForm.getUsername());
                noticeMapper.updateById(x);
            });
        }


        QueryWrapper<Noticefile> noticefileQueryWrapper = new QueryWrapper<>();
        noticefileQueryWrapper.eq("user_id",userId);
        List<Noticefile> noticefiles = noticefileMapper.selectList(noticefileQueryWrapper);
        if(noticefiles!=null){
            noticefiles.forEach(x->{
                        x.setCreateby(teacherForm.getTeaName()).setUsername(teacherForm.getUsername());
                        noticefileMapper.updateById(x);
                    }
            );

        }


        QueryWrapper<PaperFile> paperFileQueryWrapper = new QueryWrapper<>();
        paperFileQueryWrapper.eq("tusername",user.getUsername());
        List<PaperFile> paperFiles = paperFileMapper.selectList(paperFileQueryWrapper);
        paperFiles.forEach(x->{
            x.setTusername(teacherForm.getUsername());
            paperFileMapper.updateById(x);
        });


        QueryWrapper<Records> recordsQueryWrapper = new QueryWrapper<>();
        recordsQueryWrapper.eq("user_id",userId);
        List<Records> records = recordsMapper.selectList(recordsQueryWrapper);
        records.forEach(x->{
            x.setName(teacherForm.getTeaName()).setUsername(teacherForm.getUsername()).setState(teacherForm.getState());
            recordsMapper.updateById(x);
        });


        QueryWrapper<ReportFile> reportFileQueryWrapper = new QueryWrapper<>();
        reportFileQueryWrapper.eq("tusername",user.getUsername());
        List<ReportFile> reportFiles = reportFileMapper.selectList(reportFileQueryWrapper);

        if(reportFiles!=null){
            reportFiles.forEach(x->{
                x.setTusername(teacherForm.getUsername());
                reportFileMapper.updateById(x);
            });

        }


        QueryWrapper<WenFile> wenFileQueryWrapper = new QueryWrapper<>();
        wenFileQueryWrapper.eq("tusername",user.getUsername());
        List<WenFile> wenFiles = wenFileMapper.selectList(wenFileQueryWrapper);
        wenFiles.forEach(x->{
            x.setTusername(user.getUsername());
            wenFileMapper.updateById(x);
          }
        );


        String encrypt = MD5Utils.encrypt(teacherForm.getUsername(), teacherForm.getPassword());
        user.setPassword(encrypt)
        .setName(teacherForm.getTeaName())
        .setEmail(teacherForm.getTeaEmail())
        .setSex(teacherForm.getTeaSex())
        .setPhone(teacherForm.getTeaPhone())
        .setDepartment(teacherForm.getTeaDepartment())
        .setState(teacherForm.getState())
        .setStatus(teacherForm.getStatus())
        .setUsername(teacherForm.getUsername());



        userService.updateById(user);
        teacher.setTeaName(teacherForm.getTeaName()).setTeaSex(teacherForm.getTeaSex())
                .setTeaDepartment(teacherForm.getTeaDepartment())
        .setTeaPhone(teacherForm.getTeaPhone())
        .setTeaEmail(teacherForm.getTeaEmail())
        .setTeaRecord(teacherForm.getTeaRecord())
        .setTeaPost(teacherForm.getTeaPost())
        .setTeaWx(teacherForm.getTeaWx())
        .setTeaStatus(teacherForm.getStatus());
        teacherMapper.updateById(teacher);
    }

    @Override
    public void updateTeacherSelf(User user, TeacherForm teacherForm, Teacher teacher) {
        int userId = user.getUserId();


//        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
//        categoryQueryWrapper.eq("tusername",user.getUsername());
//        List<Category> categories = categoryMapper.selectList(categoryQueryWrapper);
//        categories.forEach(x->{
//            x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
//            categoryMapper.updateById(x);
//        });


//
//        QueryWrapper<ChoCgy> choCgyQueryWrapper = new QueryWrapper<>();
//        choCgyQueryWrapper.eq("tusername",user.getUsername());
//        List<ChoCgy> choCgies = choCgyMapper.selectList(choCgyQueryWrapper);
//        if(choCgies!=null){
//            choCgies.forEach(x->{
//                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
//                choCgyMapper.updateById(x);
//            });
//
//        }
//
//
//        QueryWrapper<ChoCgyRecord> choCgyRecordQueryWrapper = new QueryWrapper<>();
//        choCgyRecordQueryWrapper.eq("tusername",user.getUsername());
//        List<ChoCgyRecord> choCgyRecords = choCgyRecordMapper.selectList(choCgyRecordQueryWrapper);
//        if(choCgyRecords!=null){
//            choCgyRecords.forEach(x->{
//                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
//                choCgyRecordMapper.updateById(x);
//            });
//        }


//        List<Defence> defences = defenceMapper.selectList(null);
//        defences.forEach(x->{
//            if(x.getTusername().equals(user.getUsername())){
//                x.setTusername(teacherForm.getUsername()).setTeaName(teacherForm.getTeaName());
//                defenceMapper.updateById(x);
//            }
//            if(x.getTusername1().equals(user.getUsername())){
//                x.setTusername1(teacherForm.getUsername()).setTeaName1(teacherForm.getTeaName());
//                defenceMapper.updateById(x);
//            }
//            if(x.getTusername2().equals(user.getUsername())){
//                x.setTusername2(teacherForm.getUsername()).setTeaName2(teacherForm.getTeaName());
//                defenceMapper.updateById(x);
//            }
//            if(x.getTusername3().equals(user.getUsername())){
//                x.setTusername3(teacherForm.getUsername()).setTeaName3(teacherForm.getTeaName());
//                defenceMapper.updateById(x);
//            }
//            if(x.getTusername4().equals(user.getUsername())){
//                x.setTusername4(teacherForm.getUsername()).setTeaName4(teacherForm.getTeaName());
//                defenceMapper.updateById(x);
//            }
//        });


//        QueryWrapper<Notice> noticeQueryWrapper = new QueryWrapper<>();
//        noticeQueryWrapper.eq("user_id",userId);
//        List<Notice> notices = noticeMapper.selectList(noticeQueryWrapper);
//        if(notices!=null){
//            notices.forEach(x->{
//                x.setCreateby(teacherForm.getTeaName()).setUsername(teacherForm.getUsername());
//                noticeMapper.updateById(x);
//            });
//        }


//        QueryWrapper<Noticefile> noticefileQueryWrapper = new QueryWrapper<>();
//        noticefileQueryWrapper.eq("user_id",userId);
//        List<Noticefile> noticefiles = noticefileMapper.selectList(noticefileQueryWrapper);
//        if(noticefiles!=null){
//            noticefiles.forEach(x->{
//                x.setCreateby(teacherForm.getTeaName()).setUsername(teacherForm.getUsername());
//                noticefileMapper.updateById(x);
//                    }
//            );
//        }

//
//        QueryWrapper<PaperFile> paperFileQueryWrapper = new QueryWrapper<>();
//        paperFileQueryWrapper.eq("tusername",user.getUsername());
//        List<PaperFile> paperFiles = paperFileMapper.selectList(paperFileQueryWrapper);
//        paperFiles.forEach(x->{
//            x.setTusername(teacherForm.getUsername());
//            paperFileMapper.updateById(x);
//        });


//        QueryWrapper<Records> recordsQueryWrapper = new QueryWrapper<>();
//        recordsQueryWrapper.eq("user_id",userId);
//        List<Records> records = recordsMapper.selectList(recordsQueryWrapper);
//        records.forEach(x->{
//            x.setName(teacherForm.getTeaName()).setUsername(teacherForm.getUsername()).setState(teacherForm.getState());
//            recordsMapper.updateById(x);
//        });



//        QueryWrapper<Report> reportQueryWrapper = new QueryWrapper<>();
//        reportQueryWrapper.eq("rep_teacher",user.getUsername());
//        Report report = reportMapper.selectOne(reportQueryWrapper);
//        if(report!=null){
//            report.setRepTeacher(teacherForm.getUsername());
//            reportMapper.updateById(report);
//        }


//        QueryWrapper<WenFile> wenFileQueryWrapper = new QueryWrapper<>();
//        wenFileQueryWrapper.eq("tusername",user.getUsername());
//        List<WenFile> wenFiles = wenFileMapper.selectList(wenFileQueryWrapper);
//        wenFiles.forEach(x->{
//                    x.setTusername(user.getUsername());
//                    wenFileMapper.updateById(x);
//                }
//        );


        user.setName(teacherForm.getTeaName())
                .setEmail(teacherForm.getTeaEmail())
                .setSex(teacherForm.getTeaSex())
                .setPhone(teacherForm.getTeaPhone())
                .setDepartment(teacherForm.getTeaDepartment())
                .setState(teacherForm.getState())
                .setStatus(teacherForm.getStatus())
                .setUsername(teacherForm.getUsername());



        userService.updateById(user);
        teacher.setTeaName(teacherForm.getTeaName()).setTeaSex(teacherForm.getTeaSex())
                .setTeaDepartment(teacherForm.getTeaDepartment())
                .setTeaPhone(teacherForm.getTeaPhone())
                .setTeaEmail(teacherForm.getTeaEmail())
                .setTeaRecord(teacherForm.getTeaRecord())
                .setTeaPost(teacherForm.getTeaPost())
                .setTeaWx(teacherForm.getTeaWx())
                .setTeaStatus(teacherForm.getStatus());
        teacherMapper.updateById(teacher);
    }
}
